//
// Created by gua on 2023/4/17.
//
#include "setjmp.h"
#include "iostream"
using namespace std;
jmp_buf buf1,buf2;

struct FibStruct{
    int final;
    int val;
    int fib(int i){
        if(i==1 || i==0){
            return 1;
        }
        val = fib(i-1)+fib(i-2);
        if(i==3){
            int state = setjmp(buf2);
            if(state==0){
//              if return val equals to 1 in this place,it will return 0 in setjmp.Strange
                longjmp(buf1,2);
            }
        }
        if(i==final){
            longjmp(buf1,1);
        }
        return val;
    }

};
int main(){
    int fibVal = 5;
    int val;
    bool start = true;
    FibStruct fibStruct;
    fibStruct.final = fibVal;
    val = setjmp(buf1);
    while(val==2 || val==0){
        if(start){
            start = false;
            fibStruct.fib(fibVal);
        }else{
            cout << "yield from fib(3):" << fibStruct.val <<endl;
            longjmp(buf2,1);
        }
    }
    cout << "end" << endl;
    return 0;
}
